// Vhall Stream Saver - Popup Script
// 插件弹窗界面和视频列表管理

class VhallPopup {
  constructor() {
    this.streams = [];
    this.nativeHostAvailable = false;
    this.isRendering = false;  // 防重复渲染标志
    this.newStreamTimeout = null;  // 防抖定时器
    this.settings = {}; // 用户设置（默认质量等）
    this.init();
  }

  async init() {
    this.setupEventListeners();
    await this.loadSettings();
    await this.loadStreams();
    await this.checkNativeHost();
    this.setupMessageListener();
  }

  // 设置事件监听器
  setupEventListeners() {
    // 刷新按钮
    document.getElementById('refreshBtn').addEventListener('click', () => {
      this.refreshStreams();
    });

    // 设置按钮
    document.getElementById('settingsBtn').addEventListener('click', () => {
      chrome.runtime.openOptionsPage();
    });

    // 帮助按钮
    document.getElementById('helpBtn').addEventListener('click', () => {
      this.showHelp();
    });

    // 清空列表按钮
    document.getElementById('clearAllBtn').addEventListener('click', () => {
      this.clearAllStreams();
    });

    // 下载管理按钮
    document.getElementById('downloadManagerBtn').addEventListener('click', () => {
      chrome.runtime.openOptionsPage();
    });
  }

  // 设置消息监听器
  setupMessageListener() {
    chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
      if (message.type === 'STREAM_DETECTED') {
        this.handleNewStream(message.data);
      }
    });
  }

  // 加载设置（默认质量）
  async loadSettings() {
    try {
      const result = await chrome.storage.local.get(['vhallSettings']);
      this.settings = result.vhallSettings || { defaultQuality: 'best' };
    } catch (error) {
      this.settings = { defaultQuality: 'best' };
    }
  }

  // 解析首选质量（根据设置或自动最佳）
  resolvePreferredQuality(hlsDomainnames, defaultQuality = 'best') {
    if (!hlsDomainnames || typeof hlsDomainnames !== 'object') return null;
    if (defaultQuality && defaultQuality !== 'best') {
      return hlsDomainnames[defaultQuality] ? defaultQuality : null;
    }
    const best = this.selectBestQuality(hlsDomainnames);
    return best ? best.quality : null;
  }

  // 生成质量选择下拉项
  generateQualityOptions(stream, selectedQuality) {
    const qualities = this.extractQualities(stream.hls_domainnames).filter(q => q && q !== '未知');
    return qualities.map(q => `<option value="${q}" ${selectedQuality === q ? 'selected' : ''}>${q}</option>`).join('');
  }

  // 获取当前选定的质量及对应 URL
  getSelectedQuality(stream) {
    if (!stream || !stream.hls_domainnames) return null;

    const qualityKey =
      stream.selectedQuality ||
      this.resolvePreferredQuality(stream.hls_domainnames, this.settings?.defaultQuality);

    if (qualityKey && stream.hls_domainnames[qualityKey]) {
      return { quality: qualityKey, url: stream.hls_domainnames[qualityKey] };
    }
    return this.selectBestQuality(stream.hls_domainnames);
  }

  // 加载流数据
  async loadStreams() {
    try {
      console.log('[Popup] Starting to load streams...');
      this.showLoading('正在加载流数据...');

      const response = await this.sendMessage({ type: 'GET_DETECTED_STREAMS' });
      console.log('[Popup] Received response:', response);

      this.hideLoading();

      if (response.success) {
        console.log('[Popup] Streams loaded successfully:', response.data);
        this.streams = response.data;
        this.renderStreams();
        this.updateStreamCount();

        if (this.streams.length === 0) {
          this.showToast('暂未检测到视频流', 'info');
        } else {
          console.log('[Popup] Stream count:', this.streams.length);
        }
      } else {
        throw new Error(response.error || '获取流数据失败');
      }
    } catch (error) {
      this.hideLoading();
      console.error('[Popup] Failed to load streams:', error);
      this.showToast('加载流数据失败: ' + error.message, 'error');
    }
  }

  // 检查 Native Host 状态
  async checkNativeHost() {
    const statusElement = document.getElementById('nativeStatus');
    statusElement.textContent = '检查中...';
    statusElement.className = 'native-indicator checking';

    try {
      const response = await this.sendMessage({ type: 'CHECK_NATIVE_HOST' });
      this.nativeHostAvailable = response.available;

      if (response.available) {
        statusElement.textContent = 'yt-dlp 可用';
        statusElement.className = 'native-indicator available';
      } else {
        statusElement.textContent = 'yt-dlp 不可用';
        statusElement.className = 'native-indicator unavailable';
      }
    } catch (error) {
      console.error('[Popup] Failed to check native host:', error);
      statusElement.textContent = 'yt-dlp 不可用';
      statusElement.className = 'native-indicator unavailable';
      this.nativeHostAvailable = false;
    }
  }

  // 渲染流列表
  renderStreams() {
    console.log('[Popup] Rendering streams, count:', this.streams.length);

    // 防重复渲染：如果已经在渲染中，跳过
    if (this.isRendering) {
      console.log('[Popup] Already rendering, skipping...');
      return;
    }

    this.isRendering = true;

    try {
      const emptyState = document.getElementById('emptyState');
      const streamList = document.getElementById('streamList');

      if (this.streams.length === 0) {
        console.log('[Popup] No streams to render, showing empty state');
        emptyState.classList.remove('hidden');
        streamList.classList.add('hidden');
        return;
      }

      console.log('[Popup] Rendering stream items...');
      emptyState.classList.add('hidden');
      streamList.classList.remove('hidden');

      // 检查是否真的需要重新渲染
      const currentHTML = streamList.innerHTML;
      const newHTML = this.streams.map(stream => this.renderStreamItem(stream)).join('');

      if (currentHTML === newHTML) {
        console.log('[Popup] No changes detected, skipping DOM update');
        return;
      }

      streamList.innerHTML = newHTML;

      // 绑定下载按钮事件
      this.bindDownloadEvents();
      console.log('[Popup] Stream rendering completed');
    } finally {
      this.isRendering = false;
    }
  }

  // 渲染单个流项目
  renderStreamItem(stream) {
    const qualities = this.extractQualities(stream.hls_domainnames);
    const timeAgo = this.formatTimeAgo(stream.detected_at);
    const hasLineOptions = stream.hls_options && Object.keys(stream.hls_options).length > 0;
    const preferredQuality = stream.selectedQuality || this.resolvePreferredQuality(stream.hls_domainnames, this.settings?.defaultQuality);
    const selectedQuality = preferredQuality;

    return `
      <div class="stream-item" data-stream-id="${stream.id}">
        <div class="stream-header">
          <div class="stream-info">
            <div class="stream-title" title="${stream.video_title}">
              ${this.escapeHtml(stream.video_title)}
            </div>
            <div class="stream-url" title="${stream.page_url}">
              ${this.escapeHtml(stream.page_url)}
            </div>
          </div>
          <div class="stream-time">${timeAgo}</div>
        </div>

        <div class="stream-details">
          <div class="stream-quality">
            ${qualities.map(q => `<span class="quality-tag ${q.includes('1080') ? 'hd' : ''}">${q}</span>`).join('')}
          </div>
          <span>•</span>
          <span class="quality-selector">
            <select class="quality-select" data-stream-id="${stream.id}">
              ${this.generateQualityOptions(stream, selectedQuality)}
            </select>
          </span>
          <span>•</span>
          <span>Token: ${stream.token ? '有效' : '无效'}</span>
          ${hasLineOptions ? '<span>•</span><span class="line-selector"><select class="line-select" data-stream-id="' + stream.id + '" data-quality="' + (selectedQuality || '') + '">' + this.generateLineOptions(stream.hls_options, selectedQuality) + '</select></span>' : ''}
        </div>

        <div class="stream-actions">
          <button class="btn btn-primary btn-small download-btn" data-stream-id="${stream.id}">下载</button>
          <button class="btn btn-secondary btn-small copy-btn" data-stream-id="${stream.id}">复制命令</button>
        </div>
      </div>
    `;
  }

  // 生成线路选择选项
  generateLineOptions(hlsOptions, selectedQuality) {
    if (!hlsOptions || Object.keys(hlsOptions).length === 0) {
      return '';
    }

    let options = '';
    const qualities = Object.keys(hlsOptions);

    const qualityKey = (selectedQuality && hlsOptions[selectedQuality]) ? selectedQuality : qualities[0];
    const lines = hlsOptions[qualityKey] || [];

    lines.forEach(line => {
      options += `<option value="${line.url}" data-quality="${qualityKey}">${line.line}</option>`;
    });

    return options;
  }

  // 绑定下载事件
  bindDownloadEvents() {
    // 线路选择器事件
    document.querySelectorAll('.line-select').forEach(select => {
      select.addEventListener('change', (e) => {
        const streamId = e.target.dataset.streamId;
        const selectedUrl = e.target.value;
        const selectedQuality = e.target.options[e.target.selectedIndex].dataset.quality;

        const stream = this.streams.find(s => s.id === streamId);
        if (stream) {
          stream.selectedQuality = selectedQuality;
          stream.hls_domainnames[selectedQuality] = selectedUrl;
        }
        console.log('[Popup] Line selected:', { streamId, selectedQuality, selectedUrl });
      });
    });

    // 质量选择器事件
    document.querySelectorAll('.quality-select').forEach(select => {
      select.addEventListener('change', (e) => {
        const streamId = e.target.dataset.streamId;
        const quality = e.target.value;
        const stream = this.streams.find(s => s.id === streamId);
        if (stream) {
          stream.selectedQuality = quality;
          const lineSelect = document.querySelector(`.line-select[data-stream-id="${streamId}"]`);
          if (lineSelect && stream.hls_options) {
            lineSelect.setAttribute('data-quality', quality);
            lineSelect.innerHTML = this.generateLineOptions(stream.hls_options, quality);
            if (lineSelect.options.length > 0) {
              const first = lineSelect.options[0];
              lineSelect.value = first.value;
              stream.hls_domainnames[quality] = first.value;
            }
          }
        }
        console.log('[Popup] Quality selected:', { streamId, quality });
      });
    });

    // 下载按钮
    document.querySelectorAll('.download-btn').forEach(btn => {
      btn.addEventListener('click', (e) => {
        const streamId = e.target.closest('.download-btn').dataset.streamId;
        this.startDownload(streamId);
      });
    });

    // 复制按钮
    document.querySelectorAll('.copy-btn').forEach(btn => {
      btn.addEventListener('click', (e) => {
        const streamId = e.target.closest('.copy-btn').dataset.streamId;
        this.copyDownloadCommand(streamId);
      });
    });
  }

  // 开始下载
  async startDownload(streamId) {
    const stream = this.streams.find(s => s.id === streamId);
    if (!stream) return;

    this.showLoading('正在准备下载...');

    try {
      const selected = this.getSelectedQuality(stream);
      if (!selected) {
        throw new Error('未找到可用的视频流');
      }

      const referer = stream.referer || stream.page_url || 'https://bbs.huaweicloud.com';
      const title = stream.video_title || '华为云直播回放';

      const downloadData = {
        url: selected.url,
        referer: referer,
        title: title,
        quality: selected.quality,
        outputPath: this.generateOutputPath(title, selected.quality)
      };

      console.log('[Popup] Download data:', downloadData);

      const response = await this.sendMessage({
        type: 'START_DOWNLOAD',
        data: downloadData
      });

      this.hideLoading();

      if (response.success) {
        if (response.method === 'native') {
          this.showToast('已使用 yt-dlp 开始下载', 'success');
        } else {
          this.showToast('已使用内置下载器开始下载', 'success');
        }
      } else {
        if (response.fallback === 'command_copy') {
          // 仅复制命令，避免重复提示，由 copyDownloadCommand 显示成功提示
          await this.copyDownloadCommand(streamId);
        } else {
          throw new Error(response.error || '下载失败');
        }
      }
    } catch (error) {
      this.hideLoading();
      console.error('[Popup] Download failed:', error);
      this.showToast(`下载失败: ${error.message}`, 'error');
    }
  }

  // 复制下载命令
  async copyDownloadCommand(streamId) {
    const stream = this.streams.find(s => s.id === streamId);
    if (!stream) {
      console.error('[Popup] Stream not found for ID:', streamId);
      return;
    }

    console.log('[Popup] Copying command for stream:', {
      id: stream.id,
      title: stream.video_title,
      referer: stream.referer,
      domainnames: stream.hls_domainnames
    });

    const selected = this.getSelectedQuality(stream);
    if (!selected) {
      this.showToast('未找到可用的视频流', 'error');
      return;
    }

    console.log('[Popup] Selected quality:', selected);

    const referer = stream.referer || stream.page_url || 'https://bbs.huaweicloud.com';
    const title = stream.video_title || '华为云直播回放';

    console.log('[Popup] Using referer:', referer);
    console.log('[Popup] Using title:', title);

    const command = this.generateYtDlpCommand(selected.url, referer, title);

    try {
      await navigator.clipboard.writeText(command);
      this.showToast('下载命令已复制到剪贴板', 'success');
    } catch (error) {
      console.error('[Popup] Failed to copy command:', error);
      this.showToast('复制失败，请手动复制', 'error');
    }
  }

  // 生成 yt-dlp 命令
  generateYtDlpCommand(url, referer, title) {
    // 更好的标题处理
    let safeTitle = title;

    // 如果标题是 "Unknown Video" 或看起来异常，使用默认标题
    if (!title || title === 'Unknown Video' || title.length < 3) {
      const now = new Date();
      const dateStr = now.toISOString().split('T')[0]; // YYYY-MM-DD
      const timeStr = now.toTimeString().split(' ')[0].replace(/:/g, '-'); // HH-MM-SS
      safeTitle = `华为云直播回放_${dateStr}_${timeStr}`;
    } else {
      // 清理标题：移除特殊字符，替换空格和中文标点
      safeTitle = title
        .replace(/[^\w\u4e00-\u9fa5\s\-_().]/g, '') // 保留字母、数字、中文、空格、连字符、下划线、括号
        .replace(/[\s\u3000]+/g, '_') // 空格和全角空格替换为下划线
        .replace(/[_]+/g, '_') // 多个下划线合并为一个
        .replace(/^_+|_+$/g, '') // 去除开头和结尾的下划线
        .substring(0, 50); // 限制长度
    }

    // 如果处理后标题为空，使用默认标题
    if (!safeTitle || safeTitle.length < 1) {
      safeTitle = `华为云直播回放_${new Date().toISOString().split('T')[0]}`;
    }

    console.log('[Popup] Generated safe title:', safeTitle);
    console.log('[Popup] Generated command:', `yt-dlp "${url}" --referer "${referer}" -o "${safeTitle}.%(ext)s"`);

    return `yt-dlp "${url}" --referer "${referer}" -o "${safeTitle}.%(ext)s"`;
  }

  // 选择最佳质量
  selectBestQuality(hlsDomainnames) {
    if (!hlsDomainnames || typeof hlsDomainnames !== 'object') {
      return null;
    }

    // 质量优先级：1080p > 720p > 480p > 其他
    const priorities = ['1080p', '720p', '480p'];

    for (const quality of priorities) {
      if (hlsDomainnames[quality]) {
        return {
          quality: quality,
          url: hlsDomainnames[quality]
        };
      }
    }

    // 如果没有标准质量，选择第一个可用的
    const firstKey = Object.keys(hlsDomainnames)[0];
    if (firstKey) {
      return {
        quality: firstKey,
        url: hlsDomainnames[firstKey]
      };
    }

    return null;
  }

  // 生成输出路径
  generateOutputPath(title, quality) {
    // 使用与 generateYtDlpCommand 相同的标题处理逻辑
    let safeTitle = title;

    // 如果标题是 "Unknown Video" 或看起来异常，使用默认标题
    if (!title || title === 'Unknown Video' || title.length < 3) {
      const now = new Date();
      const dateStr = now.toISOString().split('T')[0]; // YYYY-MM-DD
      const timeStr = now.toTimeString().split(' ')[0].replace(/:/g, '-'); // HH-MM-SS
      safeTitle = `华为云直播回放_${dateStr}_${timeStr}`;
    } else {
      // 清理标题：移除特殊字符，替换空格和中文标点
      safeTitle = title
        .replace(/[^\w\u4e00-\u9fa5\s\-_().]/g, '') // 保留字母、数字、中文、空格、连字符、下划线、括号
        .replace(/[\s\u3000]+/g, '_') // 空格和全角空格替换为下划线
        .replace(/[_]+/g, '_') // 多个下划线合并为一个
        .replace(/^_+|_+$/g, '') // 去除开头和结尾的下划线
        .substring(0, 50); // 限制长度
    }

    // 如果处理后标题为空，使用默认标题
    if (!safeTitle || safeTitle.length < 1) {
      safeTitle = `华为云直播回放_${new Date().toISOString().split('T')[0]}`;
    }

    return `${safeTitle}_${quality}.%(ext)s`;
  }

  // 提取质量列表
  extractQualities(hlsDomainnames) {
    if (!hlsDomainnames || typeof hlsDomainnames !== 'object') {
      return ['未知'];
    }
    return Object.keys(hlsDomainnames);
  }

  // 格式化时间
  formatTimeAgo(dateString) {
    const now = new Date();
    const date = new Date(dateString);
    const diffMs = now - date;
    const diffMins = Math.floor(diffMs / 60000);
    const diffHours = Math.floor(diffMs / 3600000);

    if (diffMins < 1) return '刚刚';
    if (diffMins < 60) return `${diffMins}分钟前`;
    if (diffHours < 24) return `${diffHours}小时前`;
    return date.toLocaleDateString();
  }

  // 处理新流
  handleNewStream(streamData) {
    console.log('[Popup] Handling new stream:', streamData);

    // 防抖处理：如果已经有防抖定时器，清除它
    if (this.newStreamTimeout) {
      clearTimeout(this.newStreamTimeout);
    }

    // 设置防抖定时器，延迟100ms处理
    this.newStreamTimeout = setTimeout(() => {
      this.processNewStream(streamData);
    }, 100);
  }

  // 实际处理新流的逻辑
  processNewStream(streamData) {
    console.log('[Popup] Processing new stream:', streamData);

    // 检查是否已存在相同的流（基于 page_url）
    const existingStreamIndex = this.streams.findIndex(s => s.page_url === streamData.page_url);

    if (existingStreamIndex !== -1) {
      console.log('[Popup] Updating existing stream:', streamData.page_url);

      // 更新现有流的数据
      const existingStream = this.streams[existingStreamIndex];
      const hasNewData =
        existingStream.detected_at !== streamData.detected_at ||
        JSON.stringify(existingStream.hls_domainnames) !== JSON.stringify(streamData.hls_domainnames);

      if (hasNewData) {
        existingStream.detected_at = streamData.detected_at;
        // 如果有新的 HLS 信息，也更新
        if (streamData.hls_domainnames && Object.keys(streamData.hls_domainnames).length > 0) {
          existingStream.hls_domainnames = streamData.hls_domainnames;
          // 如果有新的线路选项，也更新
          if (streamData.hls_options) {
            existingStream.hls_options = streamData.hls_options;
          }
        }
        console.log('[Popup] Stream data updated, re-rendering...');
        this.renderStreams();
      } else {
        console.log('[Popup] No new data, skipping render');
      }
    } else {
      console.log('[Popup] Adding new stream:', streamData.page_url);
      // 添加新流
      this.streams.unshift(streamData);
      this.renderStreams();
      this.updateStreamCount();
      this.showToast('检测到新的视频流', 'success');
    }
  }

  // 刷新流
  async refreshStreams() {
    this.showLoading('正在刷新...');
    await this.loadStreams();
    await this.checkNativeHost();
    this.hideLoading();
    this.showToast('刷新完成', 'success');
  }

  // 清空所有流
  async clearAllStreams() {
    try {
      const response = await this.sendMessage({ type: 'CLEAR_DETECTED_STREAMS' });
      if (response.success) {
        this.streams = [];
        this.renderStreams();
        this.updateStreamCount();
        this.showToast('列表已清空', 'success');
      }
    } catch (error) {
      console.error('[Popup] Failed to clear streams:', error);
      this.showToast('清空失败', 'error');
    }
  }

  // 更新流计数
  updateStreamCount() {
    document.getElementById('streamCount').textContent = this.streams.length;
  }

  // 显示帮助
  showHelp() {
    const helpText = `
使用说明：
1. 访问微吼直播页面
2. 插件会自动检测视频流
3. 点击下载按钮开始下载
4. 如果 yt-dlp 不可用，会复制命令到剪贴板

支持的网站：
- gslb.e.vhall.com
- *.vhallyun.com
- *.vhall.com
    `;
    alert(helpText);
  }

  // 发送消息到 background
  sendMessage(message) {
    return new Promise((resolve, reject) => {
      chrome.runtime.sendMessage(message, (response) => {
        if (chrome.runtime.lastError) {
          reject(new Error(chrome.runtime.lastError.message));
        } else {
          resolve(response);
        }
      });
    });
  }

  // 显示加载状态
  showLoading(text = '正在处理...') {
    const overlay = document.getElementById('loadingOverlay');
    const loadingText = overlay.querySelector('.loading-text');
    loadingText.textContent = text;
    overlay.classList.remove('hidden');
  }

  // 隐藏加载状态
  hideLoading() {
    document.getElementById('loadingOverlay').classList.add('hidden');
  }

  // 显示提示消息
  showToast(message, type = 'info') {
    const container = document.getElementById('toastContainer');
    const toast = document.createElement('div');
    toast.className = `toast ${type}`;

    toast.innerHTML = `
      <div class="toast-message">${this.escapeHtml(message)}</div>
      <button class="toast-close">×</button>
    `;

    // 添加关闭事件
    toast.querySelector('.toast-close').addEventListener('click', () => {
      toast.remove();
    });

    container.appendChild(toast);

    // 自动移除
    setTimeout(() => {
      if (toast.parentNode) {
        toast.remove();
      }
    }, 5000);
  }

  // HTML 转义
  escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
  }

  // 清理资源
  cleanup() {
    // 清理防抖定时器
    if (this.newStreamTimeout) {
      clearTimeout(this.newStreamTimeout);
      this.newStreamTimeout = null;
    }
    console.log('[Popup] Cleanup completed');
  }
}

// 初始化 Popup
document.addEventListener('DOMContentLoaded', () => {
  new VhallPopup();
});
